//
//  MBLoginController.m
//  MiBaoTu
//
//  Created by 彭鹏 on 16/9/22.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBLoginController.h"
#import "MBRegisterController.h"
#import "MBNavController.h"
#import "MBLookForPasswordController.h"
#import "MBTabBarController.h"
#import "UIViewController+HUD.h"
#import "HTTPManager.h"
#import "ErrorMessage.h"
#import "NSString+MD5String.h"
#import "MBThirdLoginController.h"

#import "AppDelegate.h"
#import "AFNetworking.h"
#import "WeiboSDK.h"
#import "WXApi.h"
#define APP_REDIRECT_URL @"http://sina.com"
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/TencentApiInterface.h>
#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <UMMobClick/MobClick.h>

@interface MBLoginController ()<UITextFieldDelegate,WeiBoDelegate,TencentSessionDelegate,WXDelegate>
{
    AppDelegate *appdelegate;
    TencentOAuth *_tencentOAuth;
    NSMutableArray *_permissionArray;   //权限列表
}
@property (weak, nonatomic) IBOutlet UIView *phoneView;
@property (weak, nonatomic) IBOutlet UIView *passwordView;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (weak, nonatomic) IBOutlet UITextField *accountTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *phoneViewLeft;
@property (weak, nonatomic) IBOutlet UIButton *vistorBt;

@end

@implementation MBLoginController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
     [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [self setupUI];
    
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (ISIPAD) {
        _phoneViewLeft.constant = (SCREEN_WIDTH-700*PERCEN)/2.;
        _vistorBt.layer.cornerRadius = 5.f;
        _vistorBt.layer.masksToBounds = YES;
        
        _vistorBt.frame=CGRectMake(_loginBtn.left, _loginBtn.bottom+30*PERCEN, _loginBtn.width, _loginBtn.height);
        _vistorBt.titleLabel.font=[UIFont systemFontOfSize:32*PERCEN];
        _vistorBt.layer.borderColor = TINK_COLOR.CGColor;
        _vistorBt.layer.borderWidth =1.f;
        [_vistorBt setTitleColor:TINK_COLOR forState:UIControlStateNormal];
        
        _loginBtn.titleLabel.font=[UIFont systemFontOfSize:32*PERCEN];

    }

}
- (void)setupUI {
    if (IOS7) {
        [self setAutomaticallyAdjustsScrollViewInsets:NO];
    }
    
    self.phoneView.layer.cornerRadius = 5.0;
    self.phoneView.clipsToBounds = YES;
    self.phoneView.layer.borderWidth = 1*PERCEN;
    self.phoneView.layer.borderColor = UIColorFromHex(0xcccccc).CGColor;
    self.passwordView.layer.cornerRadius = 5.0;
    self.passwordView.clipsToBounds = YES;
    self.passwordView.layer.borderWidth = 1*PERCEN;
    self.passwordView.layer.borderColor = UIColorFromHex(0xcccccc).CGColor;
    self.loginBtn.layer.cornerRadius = 5.0;
    self.loginBtn.clipsToBounds = YES;
    NSString *account = [[NSUserDefaults standardUserDefaults] objectForKey:@"UserPhone"];
    NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:@"UserPwd"];
    if (account && password) {
        _accountTextField.text = account;
        if (password.length>20) {
            _passwordTextField.text = @"******";
        }else{
            _passwordTextField.text = password;
        }
        
    }
    _passwordTextField.delegate = self;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHideKeyboard)];
    [self.view addGestureRecognizer:tap];
    
    if (ISIPAD) {
        _phoneViewLeft.constant = (SCREEN_WIDTH-700*PERCEN)/2.;
        _vistorBt.layer.cornerRadius = 5.f;
        _vistorBt.layer.masksToBounds = YES;
      
        _vistorBt.frame=CGRectMake(_loginBtn.left, _loginBtn.bottom+30*PERCEN, _loginBtn.width, _loginBtn.height);
        _vistorBt.titleLabel.font=[UIFont systemFontOfSize:32*PERCEN];
        _vistorBt.layer.borderColor = TINK_COLOR.CGColor;
        _vistorBt.layer.borderWidth =1.f;
        [_vistorBt setTitleColor:TINK_COLOR forState:UIControlStateNormal];
    }
    
    NSString *login_iphone = [[NSUserDefaults standardUserDefaults] objectForKey:@"login_phone"];
    if (login_iphone.length > 0) {
        _accountTextField.text = login_iphone;
    }
}

- (void)onUpdateUIForView:(UIDeviceOrientation)orientation
{
    if (ISIPAD) {
        _phoneViewLeft.constant = (SCREEN_WIDTH-700*PERCEN)/2.;
    }
}

- (void)tapHideKeyboard{
    [_accountTextField resignFirstResponder];
    [_passwordTextField resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField == _accountTextField) {
        [_passwordTextField becomeFirstResponder];
    }else{
        [_passwordTextField resignFirstResponder];
    }
    return YES;
}


- (BOOL)validateInput{
    if ([_accountTextField.text isEqual:@""]) {
        NSLog(@"请输入手机号");
        [ErrorMessage showErrorMessage:@"请输入手机号" inView:self.view];
        return NO;
    }
    if ([_passwordTextField.text isEqual:@""]) {
        NSLog(@"请输入密码");
        [ErrorMessage showErrorMessage:@"请输入密码" inView:self.view];
        
        return NO;
    }
    return YES;
}
#pragma mark -微博登录-------------------------
- (IBAction)weiboLogin:(id)sender {
    appdelegate.weiboDelegate = self;
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    
    //回调地址与 新浪微博开放平台中 我的应用  --- 应用信息 -----高级应用    -----授权设置 ---应用回调中的url保持一致就好了
    request.redirectURI = K_Share_Url;
    
    //SCOPE 授权说明参考  http://open.weibo.com/wiki/
    request.scope = @"all";
    request.userInfo = nil;
    [WeiboSDK sendRequest:request];
    
}

//登录回调页面
-(void)weiboLoginByResponse:(WBBaseResponse *)response{
    NSDictionary *dictionary = (NSDictionary *) response.userInfo;
    NSLog(@"userinfo %@",dictionary);
    if (dictionary.allKeys.count > 0) {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager GET:[NSString stringWithFormat:@"https://api.weibo.com/2/users/show.json?access_token=%@&uid=%@",[dictionary objectForKey:@"access_token"],[dictionary objectForKey:@"uid"]] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            //开发人员拿到相关微信用户信息后， 需要与后台对接，进行登录
            MBThirdLoginController *thirdLoginVC = [[MBThirdLoginController alloc] init];
            thirdLoginVC.openID = [dictionary objectForKey:@"access_token"];//_tencentOAuth.openId;
            thirdLoginVC.nickName = [dic objectForKey:@"screen_name"];
            thirdLoginVC.picImgName = [dic objectForKey:@"profile_image_url"];
            thirdLoginVC.type = ThirdLoginType_WX;
            thirdLoginVC.formBaseViewCtrl = self.formBaseViewCtrl;
            [self.navigationController pushViewController:thirdLoginVC animated:YES];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"error %ld",(long)error.code);
        }];
    }
    
}

#pragma mark - 微信登录------------------------
- (IBAction)wechat:(id)sender {
    if ([WXApi isWXAppInstalled]) {
        SendAuthReq *req = [[SendAuthReq alloc]init];
        req.scope = @"snsapi_userinfo";
        req.openID = K_WX_AppID;
        req.state = @"1245";
        appdelegate = [UIApplication sharedApplication].delegate;
        appdelegate.wxDelegate = self;
        
        [WXApi sendReq:req];
    }else{
        //把微信登录的按钮隐藏掉。
    }
}
#pragma mark 微信登录回调
-(void)loginSuccessByCode:(NSString *)code{
    NSLog(@"code %@",code);
    __weak typeof(*&self) weakSelf = self;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];//响应
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json",@"text/plain", nil];
    //通过 appid  secret 认证code . 来发送获取 access_token的请求
    [manager GET:[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",K_WX_AppID,K_WX_AppSecret,code] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {  //获得access_token，然后根据access_token获取用户信息请求。
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"dic %@",dic);
        
        /*
         access_token	接口调用凭证
         expires_in	access_token接口调用凭证超时时间，单位（秒）
         refresh_token	用户刷新access_token
         openid	授权用户唯一标识
         scope	用户授权的作用域，使用逗号（,）分隔
         unionid	 当且仅当该移动应用已获得该用户的userinfo授权时，才会出现该字段
         */
        NSString* accessToken=[dic valueForKey:@"access_token"];
        NSString* openID=[dic valueForKey:@"openid"];
        [weakSelf requestUserInfoByToken:accessToken andOpenid:openID];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error %@",error.localizedFailureReason);
    }];
    
}

-(void)requestUserInfoByToken:(NSString *)token andOpenid:(NSString *)openID{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,openID] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        //开发人员拿到相关微信用户信息后， 需要与后台对接，进行登录
        MBThirdLoginController *thirdLoginVC = [[MBThirdLoginController alloc] init];
        thirdLoginVC.openID = openID;//_tencentOAuth.openId;
        thirdLoginVC.nickName = [dic objectForKey:@"nickname"];
        thirdLoginVC.picImgName = [dic objectForKey:@"headimgurl"];
        thirdLoginVC.type = ThirdLoginType_WX;
        thirdLoginVC.formBaseViewCtrl = self.formBaseViewCtrl;
        [self.navigationController pushViewController:thirdLoginVC animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error %ld",(long)error.code);
    }];
}

- (void)wechatLogin {
    if ([WXApi isWXAppInstalled]) {
        SendAuthReq *req = [[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo";
        req.state = @"GSTDoctorApp";
        [WXApi sendReq:req];
    }
    else {
        [self setupAlertController];
    }
}
#pragma mark - 设置弹出提示语
- (void)setupAlertController {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先安装微信客户端" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:actionConfirm];
    [self presentViewController:alert animated:YES completion:nil];
    
}

#pragma mark - QQ登录-------------------------
- (IBAction)QQlogin:(id)sender {
    
    _tencentOAuth=[[TencentOAuth alloc]initWithAppId:K_QQ_AppId andDelegate:self];
    _tencentOAuth.redirectURI = @"www.qq.com";
    
    //设置权限数据 ， 具体的权限名，在sdkdef.h 文件中查看。
    _permissionArray = [NSMutableArray arrayWithObjects: kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,nil];
   
    //登录操作
    [_tencentOAuth authorize:_permissionArray inSafari:NO];

}

/**
 * 登录成功后的回调
 */
- (void)tencentDidLogin{
    if (_tencentOAuth.accessToken && 0 != [_tencentOAuth.accessToken length])
    {
        //  记录登录用户的OpenID、Token以及过期时间
        [_tencentOAuth getUserInfo];
    }
}

/**
 * 登录失败后的回调
 * \param cancelled 代表用户是否主动退出登录
 */
- (void)tencentDidNotLogin:(BOOL)cancelled{

}

/**
 * 登录时网络有问题的回调
 */
- (void)tencentDidNotNetWork{
    //NSLog(@"没有网络了， 怎么登录成功呢");
}


#pragma mark 登录成功后，回调 - 返回对应QQ的相关信息

- (void)getUserInfoResponse:(APIResponse*) response{
    
    //这里 与自己服务器进行对接，看怎么利用这获取到的个人信息。
    
    NSDictionary *dic = response.jsonResponse;
    NSLog(@" response %@",dic);
    MBThirdLoginController *thirdLoginVC = [[MBThirdLoginController alloc] init];
    thirdLoginVC.openID = _tencentOAuth.openId;
    thirdLoginVC.nickName = [response.jsonResponse objectForKey:@"nickname"];
    thirdLoginVC.picImgName = [response.jsonResponse objectForKey:@"figureurl_qq_2"];
    thirdLoginVC.type = ThirdLoginType_QQ;
    thirdLoginVC.formBaseViewCtrl = self.formBaseViewCtrl;
    [self.navigationController pushViewController:thirdLoginVC animated:YES];
    
}

//跳转到找回密码页面
- (IBAction)lookForPasswordBtn:(id)sender {
    MBLookForPasswordController *lookForPasswordVC = [[MBLookForPasswordController alloc] init];
    lookForPasswordVC.title = @"找回密码";
    [self.navigationController pushViewController:lookForPasswordVC animated:YES];
}

//跳转到注册页面
- (IBAction)registerBtn:(id)sender {
    [self tapHideKeyboard];
    MBRegisterController *registerVC = [[MBRegisterController alloc] init];
    registerVC.formBaseViewCtrl = _formBaseViewCtrl;
    registerVC.title = @"注册";
    [self.navigationController pushViewController:registerVC animated:YES];
}
//跳转到登录页面
- (IBAction)loginBtn:(UIButton *)btn {
    if (![self validateInput]) {
        return;
    }
    
    [self tapHideKeyboard];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"登录中...";
    

    [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:LOGIN_URL_PATH,_accountTextField.text,[NSString stringWithMD5Encrypt:_passwordTextField.text]] view:nil success:^(NSDictionary * json) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([json[@"ret_code"] integerValue]==0) {
            
            //信息保存
            NSDictionary *data = json[@"data"];
            if (data.allKeys.count == 0) return ;
            UserModel *model = [UserModel objectWithKeyValues:data];
            [[UserManager standerDefult] setUserModel:model];
            
            NSArray *collecitonArr = json[@"AudioIDList"];
            if ([collecitonArr isKindOfClass:[NSArray class]]) {
                [[UserManager standerDefult].collectionMusicArr removeAllObjects];
                [[UserManager standerDefult].collectionMusicArr addObjectsFromArray:collecitonArr];
            }
            NSArray *colleciton2Arr = json[@"AlbumIDList"];
            if ([colleciton2Arr isKindOfClass:[NSArray class]]) {
                [[UserManager standerDefult].collectionAlbumArr removeAllObjects];
                [[UserManager standerDefult].collectionAlbumArr addObjectsFromArray:colleciton2Arr];
            }
            NSArray *colleciton3Arr = json[@"ShowIDList"];
            if ([colleciton3Arr isKindOfClass:[NSArray class]]) {
                [[UserManager standerDefult].collectionShowArr removeAllObjects];
                [[UserManager standerDefult].collectionShowArr addObjectsFromArray:colleciton3Arr];
            }
            
            NSArray *praiseListArr = json[@"PraiseList"];
            if ([praiseListArr isKindOfClass:[NSArray class]]) {
                [[UserManager standerDefult].praiseListArr removeAllObjects];
                [[UserManager standerDefult].praiseListArr addObjectsFromArray:praiseListArr];
            }
            
            //保存密码
            NSDate *date = [NSDate date];
            NSDateFormatter  *formatter = [[NSDateFormatter alloc]init];
            [formatter setDateFormat:@"yyyyMMdd"];
            NSString *dateStr = [formatter stringFromDate:date];
            [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%@_%@",dateStr,_passwordTextField.text] forKey:@"login_answer"];
            [[NSUserDefaults standardUserDefaults]setObject:_accountTextField.text forKey:@"login_phone"];
            [[NSUserDefaults standardUserDefaults]setObject:@{} forKey:@"three_login"];
            [[NSUserDefaults standardUserDefaults]synchronize];
            
            //统计
            [MobClick profileSignInWithPUID:_accountTextField.text];
            
            //跳转
            if (_isFormTabbar) {
                [self visitorBtn:nil];
            } else {
                
                [self.navigationController popViewControllerAnimated:YES];
            }
        } else {
            [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [ErrorMessage showErrorMessage:@"登录失败，请重试!" inView:self.view];
    }];
}

//跳转到游客模式
- (IBAction)visitorBtn:(id)sender {
    
    MBTabBarController *tabBar = [[MBTabBarController alloc] init];
    if (_isFormTabbar) {
        [UIApplication sharedApplication].keyWindow.rootViewController = tabBar;
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
@end
